package cn.jasonone.hm.netdisc.service.impl;

import cn.jasonone.hm.netdisc.mapper.FileTypeMapper;
import cn.jasonone.hm.netdisc.model.pojo.FileType;
import cn.jasonone.hm.netdisc.model.pojo.UserInfo;
import cn.jasonone.hm.netdisc.service.FileTypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import java.util.List;

/**
 * @author monster
 * @create 2020-07-24 12:10
 */
@Service
public class FileTypeServiceImpl implements FileTypeService {
    @Resource
    private FileTypeMapper fileTypeMapper;
    @Override
    public FileType findById(Integer integer) {
        return fileTypeMapper.findById(integer);
    }

    @Override
    public List<FileType> findAll(FileType fileType) {
        if (fileType == null) {
            fileType=new FileType();
            fileType.setLogicallyDelete(0);
            fileType.setState(0);
        }else{
            if(fileType.getLogicallyDelete() == null){
                fileType.setLogicallyDelete(0);
            }
            if(fileType.getState() == null){
                fileType.setState(0);
            }
        }
        return fileTypeMapper.findAll(fileType);
    }

    @Override
    public PageInfo<FileType> findAll(FileType fileType, int page, int limit) {
        PageHelper.startPage(page, limit);
        List<FileType> fileTypes = this.fileTypeMapper.findAll(fileType);
        return new PageInfo<>(fileTypes);
    }

    @Override
    public void save(FileType fileType) {
        if(fileType.getState()==null){
            fileType.setState(0);
        }
        if(fileType.getLogicallyDelete() == null){
            fileType.setLogicallyDelete(0);
        }
        this.fileTypeMapper.save(fileType);
    }

    @Override
    public void deleteByIds(boolean logical, Integer... ids) {
        this.fileTypeMapper.deleteByIds(logical, ids);
    }

    @Override
    public void delete(boolean logical, FileType fileType) {
        this.fileTypeMapper.delete(logical, fileType);
    }
    
    @Override
    public FileType parseFileType(byte[] headers) {
        List<FileType> fileTypes = this.findAll(null);
        HexBinaryAdapter hba = new HexBinaryAdapter();
        String marshal = hba.marshal(headers);//将文件头字节数组转换为16进制字符串
        FileType type=null;
        for (FileType fileType : fileTypes) {
            if(marshal.startsWith(fileType.getMagicNumber())){
                if(type==null||type.getMagicNumber().length()<fileType.getMagicNumber().length()){
                    type=fileType;
                }
            }
        }
        return type;
    }
}
